package com.univhis.service;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.univhis.entity.Log;
import com.univhis.entity.User;
import com.univhis.mapper.LogMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2024/1/5 9:03
 */
@Service
public class LogService extends ServiceImpl<LogMapper, Log> {
    @Resource
    private LogMapper logMapper;

    @Resource
    private HttpServletRequest request;

    @Resource
    private UserService userService;

    /**
     * 此时这个 getUser() 方法是作为获取用户信息的，
     * 但是此时用户的信息不是简单的JSON字符串，
     * 是经过JWT权限认证加密后的产物
     * @return
     */
    public User getUser() {
        try {
            String token = request.getHeader("token");
            String username = JWT.decode(token).getAudience().get(0);
            // Wrappers: Mybatis-Plus 选择器对象
            // lambdaQuery: 表示当前 MP 的搜索操作
            // eq: 该方法判断是否相等
            // User: getUsername: 实际上表示 User类 中的 getUsername 方法
            return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 日志记录
     */
    public void log(String content) {
        Log log = new Log();
        log.setUser(getUser().getUsername());
        log.setTime(DateUtil.formatDateTime(new Date()));
        log.setIp(getIpAddress());
        log.setContent(content);
        save(log);
    }

    /**
     * 获取 ip 地址
     */
    public String getIpAddress() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
